package com.rexolar.openapi.job;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.rexolar.openapi.db.entity.PaasPartnerApp;
import com.rexolar.openapi.enums.PartnerStatusEnum;
import com.rexolar.openapi.service.impl.PartnerAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AppSyncJob {
    @Autowired
    PartnerAppService partnerAppService;

    public static final Cache<String, String> partnerMap = CacheBuilder.newBuilder()
            .expireAfterWrite(4, TimeUnit.HOURS)
            .build();

    public String getPartnerSecret(String appKey){
        String partnerSecret = partnerMap.getIfPresent(appKey);
        if(StringUtils.isNotBlank(partnerSecret)){
            return partnerSecret;
        }
        partnerSecret = partnerAppService.fetchAppSecret(appKey);
        if(StringUtils.isBlank(partnerSecret)){
            log.error("AppSyncJob$getPartnerSecret error, appSecret is blank!appKey:{}, appSecret:{}", appKey, partnerSecret);
            return null;
        }
        partnerMap.put(appKey, partnerSecret);
        return partnerSecret;
    }

    /**
     *
     */
    @Scheduled(fixedRate = 60 * 1000)
    public void syncPartnerInfo() {
        List<PaasPartnerApp> list = partnerAppService.list();
        log.warn("syncPartnerInfo list size:{}", list.size());
        for (PaasPartnerApp app : list) {
            if (PartnerStatusEnum.ON.getCode() == app.getStatus()) {
                partnerMap.put(app.getPartnerCode(), app.getPartnerSecret());
            } else {
                partnerMap.invalidate(app.getPartnerCode());
            }
        }
    }
}